﻿using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Bulbs;
using JetBrains.ReSharper.Feature.Services.Bulk;
using JetBrains.ReSharper.Feature.Services.Bulk.Actions;
using JetBrains.ReSharper.Feature.Services.Daemon;
using JetBrains.ReSharper.Feature.Services.Intentions;
using JetBrains.ReSharper.Feature.Services.QuickFixes;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.TextControl;
using JetBrains.Util;

namespace ReSharePoint.Basic.Inspection.Common.QuickFix
{
    public abstract class SPQuickFix<THighlighting, TElement> : QuickFixBase, IHighlightingsSetAction
        where THighlighting : class, ISPHighlighting<TElement>
        where TElement : ITreeNode
    {
        protected readonly THighlighting _highlighting;

        public SPQuickFix([NotNull] THighlighting highlighting)
        {
            _highlighting = highlighting;
        }

        public override IEnumerable<IntentionAction> CreateBulbItems()
        {
            return this.ToQuickFixAction();
        }

        public string BulkText
        {
            get { return "here and"; }
        }
        
        public bool Single
        {
            get { return false; }
        }

        protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
        {
            if (_highlighting.Element.IsValid())
            {
                Fix(_highlighting.Element);
            }

            return null;
        }

        public Action<ITextControl> ExecuteAction(IEnumerable<HighlightingInfo> highlightings, ISolution solution, IProgressIndicator progress)
        {
            foreach (HighlightingInfo highlightingInfo in highlightings.AsList().WithProgress(progress, BulkText))
            {
                THighlighting highlighting = highlightingInfo.Highlighting as THighlighting;
                if (highlighting != null && highlighting.Element.IsValid())
                {
                    Fix(highlighting.Element);
                }
            }

            return null;
        }

        public abstract FileCollectorInfo FileCollectorInfo { get; }
        protected abstract void Fix(TElement element);
    }
}
